package yrjdezu.abab.engineerpractice2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import yrjdezu.abab.engineerpractice2.domain.dto.UserDTO;
import yrjdezu.abab.engineerpractice2.domain.entity.Users;
import yrjdezu.abab.engineerpractice2.mapper.UsersMapper;
import yrjdezu.abab.engineerpractice2.service.IUsersService;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2025-05-18
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    private static final Logger log = LoggerFactory.getLogger(UsersServiceImpl.class);

    @Override
    public Users login(UserDTO userDTO) {
        log.info("尝试登录：{}", userDTO.getUsername());

        // 支持用户名或邮箱登录 - 使用or条件
        return lambdaQuery()
                .and(wrapper -> wrapper
                        .eq(Users::getUsername, userDTO.getUsername())
                        .or()
                        .eq(Users::getEmail, userDTO.getEmail())
                )
                .eq(Users::getPassword, userDTO.getPassword())
                .one();
    }

    @Override
    public Users register(UserDTO userDTO) {
        // 检查用户名是否已经存在
        Long countUsername = lambdaQuery()
                .eq(Users::getUsername, userDTO.getUsername())
                .count();
        if (countUsername > 0) {
            return null; // 用户名已存在，表示注册失败
        }

        // 检查邮箱是否已经存在
        Long countEmail = lambdaQuery()
                .eq(Users::getEmail, userDTO.getEmail())
                .count();
        if (countEmail > 0) {
            // 返回特殊标记，表示邮箱已存在
            Users user = new Users();
            user.setId(-1); // 使用-1表示邮箱已存在的特殊情况
            return user;
        }

        // 创建新用户
        Users user = new Users();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setEmail(userDTO.getEmail());
        user.setUserSpace(2199023255552L);

        // 保存用户并返回
        save(user);
        return user;
    }
}
